﻿/***********************************************************************
 *            Project: CoreCms
 *        ProjectName: 核心内容管理系统                                
 *                Web: https://www.corecms.net                      
 *             Author: 大灰灰                                          
 *              Email: jianweie@163.com                                
 *         CreateTime: 2021/1/31 21:45:10
 *        Description: 暂无
 ***********************************************************************/


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Aop.Api.Domain;
using AutoMapper;
using CoreCms.Net.Auth.HttpContextUser;
using CoreCms.Net.Configuration;
using CoreCms.Net.DTO.ComponentsDTO;
using CoreCms.Net.IServices;
using CoreCms.Net.Model.Entities;
using CoreCms.Net.Model.Entities.Expression;
using CoreCms.Net.Model.FromBody;
using CoreCms.Net.Model.ViewModels.DTO;
using CoreCms.Net.Model.ViewModels.UI;
using CoreCms.Net.Services;
using CoreCms.Net.Utility.Extensions;
using CoreCms.Net.Utility.Helper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using SqlSugar;

namespace CoreCms.Net.Web.WebApi.Controllers
{
    /// <summary>
    /// 商品相关接口处理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class GoodController : ControllerBase
    {
        private IMapper _mapper;
        private readonly IHttpContextUser _user;

        private ICoreCmsSettingServices _settingServices;
        private ICoreCmsGoodsCategoryServices _goodsCategoryServices;
        private ICoreCmsGoodsServices _goodsServices;
        private ICoreCmsProductsServices _productsServices;
        private ICoreCmsBrandServices _brandServices;
        private ICoreCmsOrderItemServices _orderItemServices;
        private ICoreCmsGoodsCommentServices _goodsCommentServices;
        private ICoreCmsGoodsParamsServices _goodsParamsServices;
        private ICoreCmsGoodsCollectionServices _goodsCollectionServices;
        private ICoreCmsUserServices _userServices;
        private ICoreCmsAgentServices _agentServices;
        private ICoreCmsAgentProductsServices _agentProductsServices;
        private ICoreCmsAgentGradeServices _agentGradeServices;
        private ICoreCmsGoodsCategoryExtendServices _goodsCategoryExtendServices;

        /// <summary>
        /// 构造函数
        /// </summary>
        public GoodController(IMapper mapper
            , IHttpContextUser user
            , ICoreCmsSettingServices settingServices
            , ICoreCmsGoodsCategoryServices goodsCategoryServices
            , ICoreCmsGoodsServices goodsServices
            , ICoreCmsProductsServices productsServices
            , ICoreCmsBrandServices brandServices
            , ICoreCmsOrderItemServices orderItemServices
            , ICoreCmsGoodsCommentServices goodsCommentServices
            , ICoreCmsGoodsParamsServices goodsParamsServices
            , ICoreCmsGoodsCollectionServices goodsCollectionServices
            , ICoreCmsUserServices userServices
            , ICoreCmsAgentServices agentServices, ICoreCmsAgentProductsServices agentProductsServices, ICoreCmsAgentGradeServices agentGradeServices, ICoreCmsGoodsCategoryExtendServices goodsCategoryExtendServices)
        {
            _mapper = mapper;
            _user = user;
            _settingServices = settingServices;
            _goodsCategoryServices = goodsCategoryServices;
            _goodsServices = goodsServices;
            _productsServices = productsServices;
            _brandServices = brandServices;
            _orderItemServices = orderItemServices;
            _goodsCommentServices = goodsCommentServices;
            _goodsParamsServices = goodsParamsServices;
            _goodsCollectionServices = goodsCollectionServices;
            _userServices = userServices;
            _agentServices = agentServices;
            _agentProductsServices = agentProductsServices;
            _agentGradeServices = agentGradeServices;
            _goodsCategoryExtendServices = goodsCategoryExtendServices;
        }

        //公共接口====================================================================================================

        #region 获取所有商品分类栏目数据
        /// <summary>
        /// 获取所有商品分类栏目数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<WebApiCallBack> GetAllCategories()
        {
            var jm = new WebApiCallBack() { status = true };

            var data = await _goodsCategoryServices.QueryListByClauseAsync(p => p.isShow == true, p => p.sort, OrderByType.Asc, true, true);

            jm.status = true;
            jm.data = GetCategories(data, 0);

            return jm;
        }

        /// <summary>
        /// 迭代方法
        /// </summary>
        /// <param name="oldCategories"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        private static List<WxGoodCategoryDto> GetCategories(List<CoreCmsGoodsCategory> oldCategories, int parentId)
        {
            List<WxGoodCategoryDto> childTree = new List<WxGoodCategoryDto>();
            var model = oldCategories.Where(p => p.parentId == parentId).ToList();
            foreach (var item in model)
            {
                var parentTree = new WxGoodCategoryDto();
                parentTree.id = item.id;
                parentTree.imageUrl = !string.IsNullOrEmpty(item.imageUrl) ? item.imageUrl : "/static/images/common/empty.png";
                parentTree.name = item.name;
                parentTree.sort = item.sort;

                childTree.Add(parentTree);

                parentTree.child = GetCategories(oldCategories, item.id);
            }
            return childTree;
        }


        #endregion

        #region 根据查询条件获取分页数据============================================================
        /// <summary>
        /// 根据查询条件获取分页数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<WebApiCallBack> GetGoodsPageList([FromBody] FMPageByWhereOrder entity)
        {
            var jm = new WebApiCallBack();

            var where = PredicateBuilder.True<GoodListDTO>();

            var className = string.Empty;
            if (!string.IsNullOrWhiteSpace(entity.where))
            {
                var obj = JsonConvert.DeserializeAnonymousType(entity.where, new
                {
                    priceFrom = "",
                    priceTo = "",
                    catId = "",
                    brandId = "",
                    labelId = "",
                    searchName = "",
                });

                if (!string.IsNullOrWhiteSpace(obj.priceFrom))
                {
                    var priceF = obj.priceFrom.ObjectToDouble(0);
                    if (priceF >= 0)
                    {
                        var f = Convert.ToDecimal(priceF);
                        where = where.And(p => p.price >= f);
                    }
                }
                if (!string.IsNullOrWhiteSpace(obj.priceTo))
                {
                    var priceT = obj.priceTo.ObjectToDouble(0);
                    if (priceT > 0)
                    {
                        var f = Convert.ToDecimal(priceT);
                        where = where.And(p => p.price <= f);
                    }
                }
                if (!string.IsNullOrWhiteSpace(obj.catId))
                {
                    var catId = obj.catId.ObjectToInt(0);
                    if (catId > 0)
                    {
                        var category = await _goodsCategoryServices.QueryByIdAsync(catId, true, true);
                        if (category != null)
                        {
                            className = category.name;
                        }

                        var categories = await _goodsCategoryServices.QueryAsync(true, true);
                        var ids = GoodsHelper.GetChildIds(categories, catId);
                        //扩展分类
                        var extends = await _goodsCategoryExtendServices.QueryListByClauseAsync(p => p.goodsCategroyId == catId);
                        if (extends.Any())
                        {
                            var extGoodIds = extends.Select(p => p.goodsId).ToList();
                            where = where.And(p => ids.Contains(p.goodsCategoryId) || extGoodIds.Contains(p.id));
                        }
                        else
                        {
                            where = where.And(p => ids.Contains(p.goodsCategoryId));
                        }
                    }
                }
                if (!string.IsNullOrWhiteSpace(obj.brandId))
                {
                    if (obj.brandId.Contains(","))
                    {
                        var brandIdsIntArray = CommonHelper.StringToIntArray(obj.brandId);
                        if (brandIdsIntArray.Any())
                        {
                            where = where.And(p => brandIdsIntArray.Contains(p.brandId));
                        }
                    }
                    else
                    {
                        var brandId = obj.brandId.ObjectToInt(0);
                        if (brandId > 0)
                        {
                            where = where.And(p => p.brandId == brandId);
                        }
                    }

                }
                if (!string.IsNullOrWhiteSpace(obj.labelId))
                {
                    where = where.And(p => (',' + p.labelIds.Trim(',') + ',').Contains(',' + obj.labelId.Trim(',') + ','));
                }
                if (!string.IsNullOrWhiteSpace(obj.searchName))
                {
                    where = where.And(p => p.name.Contains(obj.searchName));
                }
            }

            //获取数据
            var list = await _goodsServices.QueryPageByDTOAsync(where, entity.order, entity.page, entity.limit, true);

            //获取品牌
            var brands = await _brandServices.QueryListByClauseAsync(p => p.isShow == true, p => p.sort, OrderByType.Desc, true, true);

            //返回数据
            jm.status = true;
            jm.data = new
            {
                list,
                className,
                entity.page,
                list.TotalCount,
                list.TotalPages,
                entity.limit,
                entity.where,
                brands
            };
            jm.msg = "数据调用成功!";

            return jm;
        }
        #endregion

        #region 根据查询条件获取分页数据============================================================       
        /// <summary>
        /// 根据查询条件获取分页数据Tow
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<WebApiCallBack> GetGoodsPageListTow([FromBody] FMPageByWhereOrder entity)
        {
            var jm = new WebApiCallBack();

            var where = PredicateBuilder.True<GoodListDTO>();

            var className = string.Empty;
            if (!string.IsNullOrWhiteSpace(entity.where))
            {
                var obj = JsonConvert.DeserializeAnonymousType(entity.where, new
                {
                    priceFrom = "",
                    priceTo = "",
                    catId = "",
                    brandId = "",
                    labelId = "",
                    searchName = "",
                });

                if (!string.IsNullOrWhiteSpace(obj.priceFrom))
                {
                    var priceF = obj.priceFrom.ObjectToDouble(0);
                    if (priceF >= 0)
                    {
                        var f = Convert.ToDecimal(priceF);
                        where = where.And(p => p.price >= f);
                    }
                }
                if (!string.IsNullOrWhiteSpace(obj.priceTo))
                {
                    var priceT = obj.priceTo.ObjectToDouble(0);
                    if (priceT > 0)
                    {
                        var f = Convert.ToDecimal(priceT);
                        where = where.And(p => p.price <= f);
                    }
                }
                if (!string.IsNullOrWhiteSpace(obj.catId))
                {
                    var catId = obj.catId.ObjectToInt(0);
                    if (catId > 0)
                    {
                        var category = await _goodsCategoryServices.QueryByIdAsync(catId, true, true);
                        if (category != null)
                        {
                            className = category.name;
                        }

                        var categories = await _goodsCategoryServices.QueryAsync(true, true);
                        var ids = GoodsHelper.GetChildIds(categories, catId);
                        //扩展分类
                        var extends = await _goodsCategoryExtendServices.QueryListByClauseAsync(p => p.goodsCategroyId == catId);
                        if (extends.Any())
                        {
                            var extGoodIds = extends.Select(p => p.goodsId).ToList();
                            where = where.And(p => ids.Contains(p.goodsCategoryId) || extGoodIds.Contains(p.id));
                        }
                        else
                        {
                            where = where.And(p => ids.Contains(p.goodsCategoryId));
                        }
                    }
                }
                if (!string.IsNullOrWhiteSpace(obj.brandId))
                {
                    if (obj.brandId.Contains(","))
                    {
                        var brandIdsIntArray = CommonHelper.StringToIntArray(obj.brandId);
                        if (brandIdsIntArray.Any())
                        {
                            where = where.And(p => brandIdsIntArray.Contains(p.brandId));
                        }
                    }
                    else
                    {
                        var brandId = obj.brandId.ObjectToInt(0);
                        if (brandId > 0)
                        {
                            where = where.And(p => p.brandId == brandId);
                        }
                    }

                }
                if (!string.IsNullOrWhiteSpace(obj.labelId))
                {
                    where = where.And(p => (',' + p.labelIds.Trim(',') + ',').Contains(',' + obj.labelId.Trim(',') + ','));
                }
                if (!string.IsNullOrWhiteSpace(obj.searchName))
                {
                    where = where.And(p => p.name.Contains(obj.searchName));
                }
            }

            //获取数据
            var list = await _goodsServices.QueryPageByDTOAsyncTow(where, entity.order, entity.page, entity.limit, true);

            //获取品牌
            var brands = await _brandServices.QueryListByClauseAsync(p => p.isShow == true, p => p.sort, OrderByType.Desc, true, true);

            //返回数据
            jm.status = true;
            jm.data = new
            {
                list,
                className,
                entity.page,
                list.TotalCount,
                list.TotalPages,
                entity.limit,
                entity.where,
                brands
            };
            jm.msg = "数据调用成功!";

            return jm;
        }
        #endregion

        #region 获取商品详情======================================================================
        /// <summary>
        /// 获取商品详情
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<WebApiCallBack> GetDetial([FromBody] FMIntId entity)
        {
            var jm = new WebApiCallBack();

            var model = await _goodsServices.GetGoodsDetail(entity.id, 0, false, "goods", 0, entity.data.ObjectToBool());
            if (model == null)
            {
                jm.msg = "商品获取失败";
                return jm;
            }

            //取类别名称
            var goodsType = new CoreCmsGoodsCategory();
            var _name = "其他";

            goodsType = await _goodsCategoryServices.QueryByClauseAsync(p => p.id == model.goodsCategoryId);

            if (goodsType.IsNotEmptyOrNull())
            {
                _name = goodsType.name.ToString();
            }

            jm.status = true;
            jm.msg = "获取商品详情成功";
            jm.data = model;
            jm.methodDescription = JsonConvert.SerializeObject(_user);
            jm.other = _name;

            return jm;
        }
        #endregion

        #region 获取单个货品信息======================================================================
        /// <summary>
        /// 获取单个货品信息
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<WebApiCallBack> GetProductInfo([FromBody] FMGetProductInfo entity)
        {
            var jm = new WebApiCallBack();

            var userId = 0;
            if (_user != null)
            {
                userId = _user.ID;
            }

            bool bl = entity.type == "pinTuan" || entity.type == "group";

            var getProductInfo = await _productsServices.GetProductInfo(entity.id, bl, userId, entity.type, entity.groupId);
            if (getProductInfo == null)
            {
                jm.msg = "获取单个货品失败";
                return jm;
            }

            jm.status = true;
            jm.msg = "获取单个货品成功";
            jm.data = getProductInfo;

            return jm;
        }

        #endregion

        #region 获取商品评价列表分页数据======================================================================
        /// <summary>
        /// 获取商品评价列表分页数据
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<WebApiCallBack> GetGoodsComment([FromBody] FMPageByIntId entity)
        {
            var jm = new WebApiCallBack();

            //获取数据
            var list = await _goodsCommentServices.QueryPageAsync(p => p.goodsId == entity.id && p.isDisplay == true, p => p.createTime, OrderByType.Desc, entity.page, entity.limit);

            if (list.Any())
            {
                foreach (var item in list)
                {
                    item.imagesArr = !string.IsNullOrEmpty(item.images) ? item.images.Split(",") : null;
                }
            }

            jm.status = true;
            jm.msg = "获取评论成功";
            jm.data = new
            {
                list,
                commentsCount = list.TotalCount,
                totalPages = list.TotalPages
            };

            return jm;
        }
        #endregion

        #region 获取商品参数======================================================================
        /// <summary>
        /// 获取单个商品参数
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<WebApiCallBack> GetGoodsParams([FromBody] FMIntId entity)
        {
            var jm = new WebApiCallBack();

            //获取数据
            var goods = await _goodsServices.QueryByIdAsync(entity.id);
            if (goods == null)
            {
                jm.msg = GlobalConstVars.DataisNo;
                return jm;
            }
            var list = new List<WxNameValueDto>();
            var goodsParams = await _goodsParamsServices.QueryAsync(true, true);

            if (!string.IsNullOrEmpty(goods.parameters))
            {
                var arrItem = goods.parameters.Split("|");
                foreach (var item in arrItem)
                {
                    if (!item.Contains(":")) continue;

                    var childArr = item.Split(":");
                    if (childArr.Length == 2)
                    {
                        var paramsId = Convert.ToInt32(childArr[0]);
                        var paramsModel = goodsParams.Find(p => p.id == paramsId);
                        if (paramsModel != null)
                        {
                            list.Add(new WxNameValueDto()
                            {
                                name = paramsModel.name,
                                value = childArr[1]
                            });
                        }
                    }
                }
            }
            jm.status = true;
            jm.msg = "获取商品参数成功";
            jm.data = list;

            return jm;
        }
        #endregion

        #region 获取随机推荐商品==================================================
        /// <summary>
        /// 获取随机推荐商品
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<WebApiCallBack> GetGoodsRecommendList([FromBody] FMIntId entity)
        {
            if (entity.id <= 0)
            {
                entity.id = 10;
            }

            var bl = entity.data.ObjectToBool();

            var jm = new WebApiCallBack()
            {
                status = true,
                code = 0,
                msg = "获取成功",
                data = await _goodsServices.GetGoodsRecommendList(entity.id, bl)
            };
            return jm;
        }
        #endregion

        #region 获取商品品牌==================================================

        /// <summary>
        /// 获取商品品牌
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<WebApiCallBack> GetAllBrands()
        {
            var jm = new WebApiCallBack() { status = true };
            var brands = await _brandServices.QueryListByClauseAsync(p => p.isShow == true, p => p.sort, OrderByType.Desc, true, true);
            jm.data = brands;
            return jm;
        }

        #endregion

        #region 根据不同类型获取不同商品数据==================================================
        /// <summary>
        /// 根据不同类型获取不同商品数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<WebApiCallBack> GetGoodsByType([FromBody] FMGetGoodByType entity)
        {
            var list = new List<GoodListDTO>();

            var orderBy = entity.orderby switch
            {
                "asc" => OrderByType.Asc,
                "desc" => OrderByType.Desc,
                _ => OrderByType.Desc
            };

            list = entity.type switch
            {
                //新品
                (int)GlobalEnumVars.SearchGoodType.New => await _goodsServices.QueryListByTypeAsync(p => p.id > 0, entity.num, p => p.createTime, orderBy, true, true, 20),
                //评论数
                (int)GlobalEnumVars.SearchGoodType.Comment => await _goodsServices.QueryListByTypeAsync(p => p.id > 0, entity.num, p => p.commentsCount, orderBy, true, true, 20),
                //销量
                (int)GlobalEnumVars.SearchGoodType.Sales => await _goodsServices.QueryListByTypeAsync(p => p.id > 0, entity.num, p => p.buyCount, orderBy, true, true, 20),
                //价格
                (int)GlobalEnumVars.SearchGoodType.Price => await _goodsServices.QueryListByTypeAsync(p => p.id > 0, entity.num, p => p.price, orderBy, true, true, 20),
                //是否推荐
                (int)GlobalEnumVars.SearchGoodType.Recommend => await _goodsServices.QueryListByTypeAsync(p => p.id > 0, entity.num, p => p.isRecommend, orderBy, true, true, 20),
                //是否参与优惠
                (int)GlobalEnumVars.SearchGoodType.Discounts => await _goodsServices.QueryListByTypeAsync(p => p.id > 0, entity.num, p => p.isInActivity, orderBy, true, true, 20),
                //综合销量
                (int)GlobalEnumVars.SearchGoodType.CombinedSalesVolume => await _goodsServices.QueryListByTypeAsync(p => p.id > 0, entity.num, p => p.initialSales, orderBy, true, true, 20),
                _ => await _goodsServices.QueryListByTypeAsync(p => p.id > 0, entity.num, p => p.createTime, orderBy, true, true, 20)
            };

            var jm = new WebApiCallBack()
            {
                status = true,
                code = 0,
                msg = "获取成功",
                data = list
            };
            return jm;
        }
        #endregion

        #region 获取商品sku======================================================================
        /// <summary>
        /// 获取商品sku
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<WebApiCallBack> GetSku([FromBody] FMGetSku entity)
        {
            var jm = new WebApiCallBack();

            var good = await _goodsServices.QueryByClauseAsync(p => p.id == entity.id, true);
            if (good == null)
            {
                jm.msg = "商品获取失败";
                return jm;
            }

            //取所有货品
            var products = await _productsServices.QueryListByClauseAsync(p => p.goodsId == good.id && p.isDel == false, p => p.id, OrderByType.Asc, true);
            if (products == null)
            {
                jm.msg = "商品sku列表获取失败";
                return jm;
            }

            var skus = await _goodsServices.GetCoreCmsProductsView(good, products, 0, entity.isPromotion, entity.type, entity.groupId);
            if (skus == null)
            {
                jm.msg = "商品sku列表组合获取失败";
                return jm;
            }
            jm.status = true;
            jm.msg = "获取商品详情成功";
            jm.data = skus;

            return jm;
        }
        #endregion

        //验证接口====================================================================================================

        #region 根据Token获取商品详情======================================================================
        /// <summary>
        /// 根据Token获取商品详情
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public async Task<WebApiCallBack> GetDetialByToken([FromBody] FMIntId entity)
        {
            var jm = new WebApiCallBack();

            var userId = 0;
            if (_user != null)
            {
                userId = _user.ID;
            }

            var user = await _userServices.QueryByClauseAsync(p => p.id == _user.ID);
            if (user == null)
            {
                jm.msg = "用户信息获取失败";
                return jm;
            }

            var model = await _goodsServices.GetGoodsDetail(entity.id, userId, false, "goods", 0, entity.data.ObjectToBool());

            if (model == null)
            {
                jm.msg = "商品获取失败";
                return jm;
            }

            var userAgent = await _agentServices.QueryByClauseAsync(p => p.userId == user.id);
            var agentProducts = new List<CoreCmsAgentProducts>();
            var userAgentGrade = new CoreCmsAgentGrade();
            if (userAgent != null)
            {
                agentProducts = await _agentProductsServices.QueryListByClauseAsync(p => p.goodId == model.id && p.isDel == false && p.agentGradeId == userAgent.gradeId);
                userAgentGrade = await _agentGradeServices.QueryByClauseAsync(p => p.id == userAgent.gradeId, true, true);
            }

            jm.otherData = new
            {
                userAgent,
                userAgentGrade,
                agentProducts
            };

            await _goodsServices.UpdateAsync(p => new CoreCmsGoods() { viewCount = p.viewCount + 1 },
                p => p.id == entity.id);

            //取类别名称
            var goodsType = new CoreCmsGoodsCategory();
            var _name = "其他";

            goodsType = await _goodsCategoryServices.QueryByClauseAsync(p => p.id == model.goodsCategoryId);

            if (goodsType.IsNotEmptyOrNull())
            {
                _name = goodsType.name.ToString();
            }

            jm.status = true;
            jm.msg = "获取商品详情成功";
            jm.data = model;
            jm.methodDescription = JsonConvert.SerializeObject(_user);
            jm.other = _name;

            return jm;
        }
        #endregion

        #region 根据Token获取商品sku======================================================================
        /// <summary>
        /// 根据Token获取商品sku
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public async Task<WebApiCallBack> GetSkuByToken([FromBody] FMGetSku entity)
        {
            var jm = new WebApiCallBack();

            var userId = 0;
            if (_user != null)
            {
                userId = _user.ID;
            }

            var good = await _goodsServices.QueryByClauseAsync(p => p.id == entity.id, true);
            if (good == null)
            {
                jm.msg = "商品获取失败";
                return jm;
            }

            //取所有货品
            var products = await _productsServices.QueryListByClauseAsync(p => p.goodsId == good.id && p.isDel == false, p => p.id, OrderByType.Asc, true);
            if (products == null)
            {
                jm.msg = "商品sku列表获取失败";
                return jm;
            }

            var skus = await _goodsServices.GetCoreCmsProductsView(good, products, userId, entity.isPromotion, entity.type, entity.groupId);
            if (skus == null)
            {
                jm.msg = "商品sku列表组合获取失败";
                return jm;
            }

            jm.status = true;
            jm.msg = "获取商品详情成功";
            jm.data = skus;

            return jm;
        }
        #endregion

        #region 商品上架

        /// <summary>
        /// 商品上架
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        //[Authorize]
        //public async Task<WebApiCallBack> GoodsGrounding([FromBody] FMGoodsInsertModel entity)
        public async Task<AdminUiCallBack> GoodsGrounding([FromBody] object value)
        {
            var jm = new AdminUiCallBack();

            //解析参数
            JObject jsonVal = JObject.Parse(value.ToString());

            string _id = jsonVal["id"].IsNotEmptyOrNull() ? jsonVal["id"].ObjectToString() : "00000000-0000-0000-0000-000000000000";

            string _isNomalVirtual = jsonVal["isNomalVirtual"].IsNotEmptyOrNull() ? jsonVal["isNomalVirtual"].ObjectToString() : "false";
            string _isMarketable = jsonVal["isMarketable"].IsNotEmptyOrNull() ? jsonVal["isMarketable"].ObjectToString() : "false";
            string _isRecommend = jsonVal["isRecommend"].IsNotEmptyOrNull() ? jsonVal["isRecommend"].ObjectToString() : "false";
            string _isHot = jsonVal["isHot"].IsNotEmptyOrNull() ? jsonVal["isHot"].ObjectToString() : "true";

            string _isDel = jsonVal["isDel"].IsNotEmptyOrNull() ? jsonVal["isDel"].ObjectToString() : "false";
            string _goodsCategoryId = jsonVal["goodsCategoryId"].IsNotEmptyOrNull() ? jsonVal["goodsCategoryId"].ObjectToString() : "2083";

            string _goodsCategory = jsonVal["goodsCategory"].IsNotEmptyOrNull() ? jsonVal["goodsCategory"].ObjectToString() : "绿茶";

            string _brandId = jsonVal["brandId"].IsNotEmptyOrNull() ? jsonVal["brandId"].ObjectToString() : "1028";
            string _brief = jsonVal["brief"].IsNotEmptyOrNull() ? jsonVal["brief"].ObjectToString() : "";


            string _mktprice = jsonVal["mktprice"].IsNotEmptyOrNull() ? jsonVal["mktprice"].ObjectToString() : "0";
            string _price = jsonVal["price"].IsNotEmptyOrNull() ? jsonVal["price"].ObjectToString() : "0";
            string _costprice = jsonVal["costprice"].IsNotEmptyOrNull() ? jsonVal["costprice"].ObjectToString() : "0";

            string _name = jsonVal["name"].IsNotEmptyOrNull() ? jsonVal["name"].ObjectToString() : "";
            string _unit = jsonVal["unit"].IsNotEmptyOrNull() ? jsonVal["unit"].ObjectToString() : "";
            string _specs = jsonVal["specs"].IsNotEmptyOrNull() ? jsonVal["specs"].ObjectToString() : "";

            string _images = jsonVal["images"].IsNotEmptyOrNull() ? jsonVal["images"].ObjectToString() : "";
            string _image = jsonVal["image"].IsNotEmptyOrNull() ? jsonVal["image"].ObjectToString() : "";

            string _province = jsonVal["province"].IsNotEmptyOrNull() ? jsonVal["province"].ToString() : "";
            string _city = jsonVal["city"].IsNotEmptyOrNull() ? jsonVal["city"].ToString() : "";
            string _area = jsonVal["area"].IsNotEmptyOrNull() ? jsonVal["area"].ToString() : "";
            string _address = jsonVal["address"].IsNotEmptyOrNull() ? jsonVal["address"].ToString() : "";

            string _lat = jsonVal["lat"].IsNotEmptyOrNull() ? jsonVal["lat"].ToString() : "";
            string _lgt = jsonVal["lng"].IsNotEmptyOrNull() ? jsonVal["lng"].ToString() : "";

            //取类别ID
            var goodsType = new CoreCmsGoodsCategory();

            goodsType = await _goodsCategoryServices.QueryByClauseAsync(p => p.name == _goodsCategory);

            if (goodsType.IsNotEmptyOrNull())
            {
                _goodsCategoryId = goodsType.id.ToString();
            }
            else
            {
                _goodsCategoryId = "2055";
            }

            //商品实体数据
            var _sn = CommonHelper.GetTimeStampByTotalMilliseconds();
            var goods = new CoreCmsGoods();
            goods.bn = "SN" + _sn.ToString();
            goods.brandId = _brandId.ObjectToInt();

            StringBuilder sb = new StringBuilder();
            sb.Append("<p>");
            sb.Append(_brief.ToString());
            sb.Append("</p>");

            List<string> list = new List<string>(_images.Split(','));
            foreach (var ls in list)
            {
                sb.AppendFormat(("<p> <img alt=\"t.png\" src=\"{0}\" /></p>"), ls);
            }

            goods.brief = _brief;
            goods.costprice = _costprice.ObjectToDecimal();
            goods.goodsCategoryId = _goodsCategoryId.ObjectToInt();
            goods.goodsTypeId = 0;

            goods.goodsSkuIds = "";
            goods.goodsParamsIds = "";

            goods.images = _images;
            goods.image = _image;
            goods.video = "";

            //item.Province = _province;
            //item.City = _city;
            //item.Area = _area;
            //item.Address = _address;
            //item.Lat = _lat;
            //item.Lgt = _lgt;

            //< p >< img alt = "" src = "http://files.mvccms.cn/Upload/20200930/20200930234931_0499.jpg" style = "height:983px; width:790px" /></ p >

            goods.intro = sb.ToString();

            //goods.intro = window.editor.getData();
            //if (!!!goods.intro)
            //{
            //    layer.msg('商品详情不能为空', { icon: 5 });
            //    return false;
            //}

            goods.isDel = false;
            goods.isHot = true;
            goods.isMarketable = true;
            goods.isNomalVirtual = false;
            goods.isRecommend = true;
            goods.mktprice = _mktprice.ObjectToDecimal();
            goods.name = _name.ObjectToString();
            goods.newSpec = _specs;
            goods.parameters = "";
            goods.productsDistributionType = 0;
            goods.price = _price.ObjectToDecimal();
            goods.sn = goods.bn;
            goods.sort = 0;
            goods.spesDesc = "";
            goods.stock = 9999;
            goods.unit = _unit;
            goods.weight = 0;
            goods.openSpec = 0;


            //多参数产品库生成列表集合
            var products = new List<CoreCmsProducts>();

            var obj = new CoreCmsProducts();
            obj.goodsId = 0;
            obj.barcode = "BN" + _sn.ToString();
            obj.sn = goods.bn;
            obj.price = _price.ObjectToDecimal();
            obj.costprice = _costprice.ObjectToDecimal();
            obj.mktprice = _mktprice.ObjectToDecimal();
            obj.marketable = true;
            obj.weight = 0;
            obj.stock = 9999;
            obj.freezeStock = 0;
            obj.spesDesc = _specs;
            obj.isDefalut = true;
            obj.images = _images;
            obj.isDel = false;
            obj.levelOne = 1;
            obj.levelTwo = 2;
            obj.levelThree = 3;
            products.Add(obj);

            var gradePrice = new List<gradePrice>();

            var obj2 = new gradePrice();
            obj2.key = 0;
            obj2.value = 100;
            gradePrice.Add(obj2);

            //var objprc = new gradePrice();
            //{
            //    public int key { get; set; }
            //    public decimal value { get; set; }
            //}

            var entity = new FMGoodsInsertModel();
            entity.goods = goods;
            entity.products = products;
            entity.goodsCategoryExtendIds = "";
            entity.gradePrice = gradePrice;


            //var productsCount = parseInt(field['productsCount']);
            //for (var i = 0; i < productsCount; i++)
            //{
            //    var productModel = { };
            //    productModel.costprice = field['product[costprice][' + i + ']'];
            //    productModel.images = field['product[images][' + i + ']'];
            //    productModel.isDefalut = true;

            //    productModel.mktprice = field['product[mktprice][' + i + ']'];
            //    productModel.price = field['product[price][' + i + ']'];
            //    productModel.sn = field['product[sn][' + i + ']'];
            //    productModel.spesDesc = field['product[spesDesc][' + i + ']'];
            //    productModel.stock = field['product[stock][' + i + ']'];
            //    productModel.weight = field['product[weight][' + i + ']'];
            //    productModel.levelOne = field['product[levelOne][' + i + ']'];
            //    productModel.levelTwo = field['product[levelTwo][' + i + ']'];
            //    productModel.levelThree = field['product[levelThree][' + i + ']'];
            //    products.push(productModel);
            //}
            //会员价格模型
            //var gradePrice = new corecmspr [];
            //if (field.gradeCount != '0')
            //{
            //    var gradeCount = parseInt(field['gradeCount']);
            //    for (var i = 0; i < gradeCount; i++)
            //    {
            //        var gradePriceChild = { };
            //        gradePriceChild.key = field['gradePrice[key][' + i + ']'];
            //        gradePriceChild.value = field['gradePrice[value][' + i + ']'];
            //        gradePrice.push(gradePriceChild);
            //    }
            //}


            //field['goods[isMarketable]'] = field['goods[isMarketable]'] == 'on';
            //field['goods[isRecommend]'] = field['goods[isRecommend]'] == 'on';
            //field['goods[isHot]'] = field['goods[isHot]'] == 'on';
            //field['goods[isDel]'] = field['goods[isDel]'] == 'on';
            //field['goods[goodsCategoryId]'] = field.goodsCategoryId;
            //if (!!!field['goods[goodsCategoryId]'])
            //{
            //    layer.msg('请选择商品栏目');
            //    return false;
            //}

            //field.goodsCategoryExtendIds = field.goodsCategoryIdExtend;
            //var keys = Object.keys(field);
            //var keysCount = 0;
            //for (var i = 0; i < keys.length; i++)
            //{
            //    if (keys[i].indexOf('paramsKey') != -1)
            //    {
            //        keysCount++;
            //    }
            //}

            //if (string.IsNullOrEmpty(entity.orderId))
            //{
            //    jm.code = 13100;
            //    jm.msg = GlobalErrorCodeVars.Code13100;
            //}
            //else if (entity.items == null || entity.items.Count == 0)
            //{
            //    jm.code = 10051;
            //    jm.msg = GlobalErrorCodeVars.Code10051;
            //}
            //jm = await _goodsCommentServices.AddComment(entity.orderId, entity.items, _user.ID);
            jm = await _goodsServices.InsertAsync(entity);

            jm.otherData = entity;
            return jm;
        }

		#endregion

		#region 编辑商品

		/// <summary>
		/// 编辑商品
		/// </summary>
		/// <returns></returns>
		[HttpPost]
		//[Authorize]
		//public async Task<WebApiCallBack> GoodsGrounding([FromBody] FMGoodsInsertModel entity)
		public async Task<AdminUiCallBack> GoodsEdit([FromBody] object value)
		{
            var jm = new AdminUiCallBack();

            //解析参数
            JObject jsonVal = JObject.Parse(value.ToString());

			string _id = jsonVal["id"].IsNotEmptyOrNull() ? jsonVal["id"].ObjectToString() : "0";

			string _isNomalVirtual = jsonVal["isNomalVirtual"].IsNotEmptyOrNull() ? jsonVal["isNomalVirtual"].ObjectToString() : "false";
			string _isMarketable = jsonVal["isMarketable"].IsNotEmptyOrNull() ? jsonVal["isMarketable"].ObjectToString() : "false";
			string _isRecommend = jsonVal["isRecommend"].IsNotEmptyOrNull() ? jsonVal["isRecommend"].ObjectToString() : "false";
			string _isHot = jsonVal["isHot"].IsNotEmptyOrNull() ? jsonVal["isHot"].ObjectToString() : "true";

			string _isDel = jsonVal["isDel"].IsNotEmptyOrNull() ? jsonVal["isDel"].ObjectToString() : "false";
			string _goodsCategoryId = jsonVal["goodsCategoryId"].IsNotEmptyOrNull() ? jsonVal["goodsCategoryId"].ObjectToString() : "2083";

			string _goodsCategory = jsonVal["goodsCategory"].IsNotEmptyOrNull() ? jsonVal["goodsCategory"].ObjectToString() : "绿茶";  //商品分类 

			string _brandId = jsonVal["brandId"].IsNotEmptyOrNull() ? jsonVal["brandId"].ObjectToString() : "1028";
			string _brief = jsonVal["brief"].IsNotEmptyOrNull() ? jsonVal["brief"].ObjectToString() : "";              //商品描述


			string _mktprice = jsonVal["mktprice"].IsNotEmptyOrNull() ? jsonVal["mktprice"].ObjectToString() : "0";    //市场价
			string _price = jsonVal["price"].IsNotEmptyOrNull() ? jsonVal["price"].ObjectToString() : "0";             //售价
			string _costprice = jsonVal["costprice"].IsNotEmptyOrNull() ? jsonVal["costprice"].ObjectToString() : "0"; //成本价

			string _name = jsonVal["name"].IsNotEmptyOrNull() ? jsonVal["name"].ObjectToString() : "";                  //标题
			string _unit = jsonVal["unit"].IsNotEmptyOrNull() ? jsonVal["unit"].ObjectToString() : "";
			string _specs = jsonVal["specs"].IsNotEmptyOrNull() ? jsonVal["specs"].ObjectToString() : "";

			string _images = jsonVal["images"].IsNotEmptyOrNull() ? jsonVal["images"].ObjectToString() : "";            //图片列表
			string _image = jsonVal["image"].IsNotEmptyOrNull() ? jsonVal["image"].ObjectToString() : "";               //封面图

			string _province = jsonVal["province"].IsNotEmptyOrNull() ? jsonVal["province"].ToString() : "";
			string _city = jsonVal["city"].IsNotEmptyOrNull() ? jsonVal["city"].ToString() : "";
			string _area = jsonVal["area"].IsNotEmptyOrNull() ? jsonVal["area"].ToString() : "";
			string _address = jsonVal["address"].IsNotEmptyOrNull() ? jsonVal["address"].ToString() : "";

			string _lat = jsonVal["lat"].IsNotEmptyOrNull() ? jsonVal["lat"].ToString() : "";
			string _lgt = jsonVal["lng"].IsNotEmptyOrNull() ? jsonVal["lng"].ToString() : "";

            var oldModel = await _goodsServices.QueryByIdAsync(int.Parse(_id));
            if (oldModel == null)
            {
                jm.msg = "不存在此信息";
                jm.data = _id;
                return jm;
            }

            jm.code = 0;

            //取类别ID
            var goodsType = new CoreCmsGoodsCategory();

			goodsType = await _goodsCategoryServices.QueryByClauseAsync(p => p.name == _goodsCategory);

			if (goodsType.IsNotEmptyOrNull())
			{
				_goodsCategoryId = goodsType.id.ToString();
			}
			else
			{
				_goodsCategoryId = "2055";
            }

            StringBuilder sb = new StringBuilder();
            sb.Append("<p>");
            sb.Append(_brief.ToString());
            sb.Append("</p>");

            List<string> list = new List<string>(_images.Split(','));
            foreach (var ls in list)
            {
                sb.AppendFormat(("<p> <img alt=\"t.png\" src=\"{0}\" /></p>"), ls);
            }

            oldModel.brief = _brief;
            oldModel.costprice = _costprice.ObjectToDecimal();
            oldModel.goodsCategoryId = _goodsCategoryId.ObjectToInt();

            oldModel.images = _images;
            oldModel.image = _image;

            oldModel.intro = sb.ToString();

            oldModel.mktprice = _mktprice.ObjectToDecimal();
            oldModel.name = _name.ObjectToString();
            oldModel.newSpec = _specs;
            oldModel.price = _price.ObjectToDecimal();
            oldModel.unit = _unit;

            var _obj = new CoreCmsProducts();
            _obj = await _productsServices.QueryByClauseAsync(p => p.goodsId == oldModel.id);

            _obj.price = _price.ObjectToDecimal();
            _obj.costprice = _costprice.ObjectToDecimal();
            _obj.mktprice = _mktprice.ObjectToDecimal();
            _obj.spesDesc = _specs;
            _obj.images = _images;
            await _productsServices.UpdateAsync(_obj);

            //事物处理过程结束
            var result = await _goodsServices.UpdateAsync(oldModel);
            //var result = true;
            var bl = result;
            jm.code = bl ? 0 : 1;
            jm.msg = bl ? GlobalConstVars.EditSuccess : GlobalConstVars.EditFailure;

			return jm;
		}

		#endregion

		#region 获取所有末级商品分类栏目数据
		/// <summary>
		/// 获取所有末级商品分类栏目数据
		/// </summary>
		/// <returns></returns>
		[HttpPost]
        public async Task<WebApiCallBack> GetChildsCategories()
        {
            var jm = new WebApiCallBack() { status = true };

            var data = await _goodsCategoryServices.QueryListByClauseAsync(p => p.isShow == true, p => p.sort,
                OrderByType.Asc);
            var wxGoodCategoryDto = new List<WxGoodCategoryDto>();
            var childsListtmp = new List<WxGoodCategoryChild>();

            var childsList = new List<WxGoodCategoryChild>();

            var parents = data.Where(p => p.parentId == 0).ToList();
            if (parents.Any())
            {
                parents.ForEach(p =>
                {
                    var model = new WxGoodCategoryDto();
                    model.id = p.id;
                    model.name = p.name;
                    model.imageUrl = !string.IsNullOrEmpty(p.imageUrl) ? p.imageUrl : "/static/images/common/empty.png";
                    model.sort = p.sort;

                    var childs = data.Where(p => p.parentId == model.id).ToList();

                    if (childs.Any())
                    {

                        childs.ForEach(o =>
                        {
                            childsListtmp.Add(new WxGoodCategoryChild()
                            {
                                id = o.id,
                                imageUrl = !string.IsNullOrEmpty(o.imageUrl) ? o.imageUrl : "/static/images/common/empty.png",
                                name = o.name,
                                sort = o.sort
                            });
                        });
                        //model.child = childsListtmp;
                    }

                    childsList = childsListtmp;
                });
            }
            jm.status = true;
            jm.data = childsList;

            return jm;
        }

        #endregion

        #region 上架商品====================================================
        /// <summary>
        /// 上架
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<WebApiCallBack> upGoods([FromBody] FMIntId entity)
        {
            var jm = new WebApiCallBack();

            if (string.IsNullOrEmpty(entity.id.ToString()))
            {
                jm.msg = "请选择要上架的商品";
                return jm;
            }
            jm = await _goodsServices.DoMarketableUp(entity.id);
            return jm;

        }
        #endregion

        #region 下架商品====================================================
        /// <summary>
        /// 下架
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<WebApiCallBack> downGoods([FromBody] FMIntId entity)
        {
            var jm = new WebApiCallBack();

            if (string.IsNullOrEmpty(entity.id.ToString()))
            {
                jm.msg = "请选择要下架的商品";
                return jm;
            }
            jm = await _goodsServices.DoMarketableDown(entity.id);
            return jm;

        }
        #endregion


    }
}